package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        //参数校验
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //分页参数校验
        dto.checkParam();

        //条件查询
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){//状态
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (dto.getKeyword()!=null){//关键字
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        if (dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){//时间区间
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        if (dto.getChannelId()!=null){//频道
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //查询当前用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){//判断是否为空
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //用户ID
        lambdaQueryWrapper.eq(WmNews::getUserId,user.getId());

        //时间倒序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //分页查询
        Page page = new Page(dto.getPage(), dto.getSize());

        IPage iPage = page(page, lambdaQueryWrapper);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;
    public static final short WM_NEWS_CONTENT_REFERENCE=1 ;//主图引用

   @Override
   @GlobalTransactional
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {

        //参数校验
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (isSubmit == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //新闻表操作 --- 将json解析为wmNews对象
        WmNews wmNews = new WmNews();

        //1）、对象浅拷贝
        BeanUtils.copyProperties(dto,wmNews);

        //2）、封面状态为自动，type则赋值为null
        if (WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }

        //3）、解析封面图片
        if (dto.getImages() != null && dto.getImages().size()>0){//images不为空切条数最少有一条
            String image = dto.getImages().toString().replace("[", "")//将[替换为空串
                    .replace("]", "")//将]替换为空串
                    .replace(" ", "")//将" "替换为空串
                    .replace(fileServerUrl, "");//将ip替换为空串
            wmNews.setImages(image);
        }

        //4）、保存新闻表
        wmNews.setCreatedTime(new Date());
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
           return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wmNews.setUserId(user.getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);

        //判断是否携带id
       if (wmNews.getId() == null){
           this.save(wmNews);
       }else {
           this.updateById(wmNews);

           //删除 素材 新闻 中间表
           QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
           queryWrapper.lambda().eq(WmNewsMaterial::getNewsId,wmNews.getId());
           wmNewsMaterialMapper.delete(queryWrapper);

       }


        //素材表操作 --- 将content转换为list集合
        String content = dto.getContent();
        List<Map> mapList = JSON.parseArray(content, Map.class);
        List<String> strings = ectractUrlInfo(mapList);

        //批量保存关系表
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode()) && strings.size()>0){
            //调用保存文章和素材关系表
            ResponseResult result = this.saveRelativeInfo(strings, wmNews.getId());
            if (result.getCode()!=0) {
                return result;
            }
        }

       //3.2 设置封面
       if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
           ResponseResult responseResult = saveRelativeInfoForCover(dto, strings, wmNews);
           if (responseResult != null) {
               return responseResult;
           }
       }

        return null;
    }

    //提取封面图片且维护封面和素材表之间的关系
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto,List<String> imageList, WmNews wmNews){
        //1:判断多图 一图 修改主表字段
        List<String> imageListNew =dto.getImages();
        if(dto.getType().equals(WM_NEWS_TYPE_AUTO)){
            if(imageList.size()>0 &&imageList.size()<=2){
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                imageListNew =imageList.stream().limit(1).collect(Collectors.toList());
            }else if(imageList.size()> 2){
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                imageListNew =imageList.stream().limit(3).collect(Collectors.toList());
            }else{
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
        }
        String imageStr=null;
        if(imageListNew.size()>0){
            imageStr =imageListNew.toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", "");

            wmNews.setImages(imageStr);
        }
        this.updateById(wmNews);

        //2:维护封面图片和素材的关系
        List<String> imageListNew1=new ArrayList<>();
        for(String s :imageListNew){
            imageListNew1.add(s.replace(fileServerUrl, ""));
        }
        ResponseResult responseResult = this.saveRelativeInfo(imageListNew1, wmNews.getId());
        return responseResult;
    }

    //图片提取
    private List<String> ectractUrlInfo(List<Map> list){

        //创建一个list集合用于存储用于存储提取出的图片路径
        List<String> imageList = new ArrayList<>();

        for (Map map : list) {
            if (map.get("type").equals(WM_NEWS_TYPE_IMAGE)){//判断type值是否为image
                String imageUrl = (String) map.get("value");
                String replace = imageUrl.replace(fileServerUrl, "");
                imageList.add(replace);
            }
        }

        //将集合返回
        return imageList;
    }

     //保存关系
    private ResponseResult saveRelativeInfo(List<String> imageList, Integer wmNewsId) {
        //1:判断提取出来的图片是否存在与素材库中
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, imageList);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId, user.getId());
        List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(lambdaQueryWrapper);

        //2:如果存在，二次过滤真实存在与素材库的图片提取，存新的List《String》
        List<String> wmMaterialListNew = new ArrayList<>();
        if (wmMaterialList.size() > 0) {
            //3: 给每条数据构建模型，map集合 key==url  value==素材id
            Map<String, Integer> map = wmMaterialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            //4: 循环wmMaterialList 过滤摸鱼的
            for (String s : imageList) {
                Integer wmId = map.get(s);
                if (wmId == null) {
                    //这是个摸鱼 库中没有的
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                } else {
                    wmMaterialListNew.add(wmId.toString());
                }
            }
        }
        //5:保存中间表
        wmNewsMaterialMapper.saveRelationsByContent(wmMaterialListNew, wmNewsId, 1);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {

       //参数校验
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据id查询数据
        WmNews wmNews = getById(id);
        //判断数据是否存在
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //返回结果
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {

       //参数校验
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据id查询数据
        WmNews wmNews = getById(id);
        //判断数据是否存在
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //文章已发布 && 上架 的不可以删除
        if (wmNews.getStatus().equals(9) && wmNews.getEnable()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"文章已上架无法删除");
        }

        //删除中间表
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));

        //删除新闻表
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        //参数校验
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据id查询数据
        WmNews wmNews = getById(dto.getId());
        //判断数据是否存在
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //检测该文章是否已发布
        if (wmNews.getStatus().equals(9)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"该文章并未发布不可进行上下架操作");
        }

        if (dto.getEnable()!=null && (dto.getEnable()==1||dto.getEnable()==0)){
            this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,dto.getId()));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {

        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        boolean b = this.updateById(wmNews);

        if (b){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

}
